//metro.js
const app = getApp();
var util = require("../../utils/util.js");
// 引用百度地图微信小程序JSAPI模块 
var bmap = require('../../utils/bmap-wx.js')
var wxMarkerData = []

Page({
  data: {
    isshow: false,    //进入页面选择1是否授权，默认不显示整个页面
    cityshow: false,  //是否显示选择城市，默认不显示
    showorclose: "showcitylist",
    cityshowimg: "down-circle",
    display: "none",
    showheight: 750,  //默认选择城市view高度750rpx
    line_id: 0,       //默认第一条线路
    istran: false,    //是否在移动
    bgcolor: '#669999',
    textcolor: '#fff',
    showstatus: 'block',
    bgcolor2: '#fff',
    textcolor2: '#669999',
    showstatus2: 'none',    
    modalHidden: true, //是否隐藏模态框，默认隐藏
    locationmodalHidden: true, 
    paymodalHidden: true,
    is_hidden: false,
    cur_city_py: "http://ditie.114huoche.com/map/shanghai.jpg",
    menu1: [{
      name: "地铁图",
      m_color: "rgba(226, 103, 74, 0.8)",
      url: "show_metro_pic"
    }, ],
    isPopping: true,    //右下角是否已经弹出    
  },  
  onLoad: function() {  //页面加载直接显示的内容    
    var today = new Date();
    var year = today.getFullYear();
    var month = today.getMonth() + 1;
    var day = today.getDate();
    var weekday = "";
    if (today.getDay() == 1) {
      weekday = "周一";
    } else if (today.getDay() == 2) {
      weekday = "周二";
    } else if (today.getDay() == 3) {
      weekday = "周三";
    } else if (today.getDay() == 4) {
      weekday = "周四";
    } else if (today.getDay() == 5) {
      weekday = "周五";
    } else if (today.getDay() == 6) {
      weekday = "周六";
    } else if (today.getDay() == 0) {
      weekday = "周日";
    }
    this.setData({
      now: year + "年" + month + "月" + day + "日",
      week: weekday,
      isshow: false
    })
    var that = this
    var BMap = new bmap.BMapWX({
      ak: 'ZenlWcczwXIAsrvdnGvFkdCSTRxWSXep'
    })
    var fail = function (data) {
      console.log("fail", data)
      that.setData({
        near_station: "定位失败",   
        near_line: '',    
      })
    }
    var success = function (data) {
      wxMarkerData = data.wxMarkerData
      if (data.wxMarkerData.length == 0) {  //周边设施为空，显示当前位置，避免报错
        that.setData({
          near_station: "附近无地铁站"
        })
      }
      else {   
        var nearstr = data.wxMarkerData[0].address
        var nearstr2 = nearstr.replace(/地铁/g, '')
        var nearstr3 = nearstr2.replace(/;/g, ' ')
        var nearfirst = ""
        if (nearstr3.split(' ')[0] == ""){
          nearfirst = ""
        }
        else{
          nearfirst = nearstr3.split(' ')[0]
        }        
        that.setData({
          near_station: data.wxMarkerData[0].title + "地铁站",
          near_line: nearstr3,
          near_station_name: data.wxMarkerData[0].title,
          near_first: nearfirst
        })
      }
    }
    // 发起POI检索地铁站
    BMap.search({
      "query": '地铁站',
      fail: fail,
      success: success      
    })

    /* 用户是否授权 获取经纬度 */    
    wx.getLocation({
      type: 'wgs84', //默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标   
      success: function(res) { //如果用户授权，点击确定，获取所在城市以及经纬度        
        var longitude = res.longitude
        var latitude = res.latitude
        that.loadCity(longitude, latitude)
        that.setData({
          isshow: true
        })
      },
      fail: function(res) { //如果用户拒绝授权，点击取消，全部值置为空
        console.log('拒绝授权');
        that.setData({
          currentCity: "",
          lng: "",
          lat: "",
          isshow: true          
        });
        that.loadPage("", "", "");
      }
    })     
  },
  onReady: function () {
    var that = this
    setTimeout(() => {
      wx.getSystemInfo({
        success: function (res) {
          let height = res.windowHeight          
          wx.createSelectorQuery().select('.line-title').boundingClientRect(function (rect) {           
            if (rect.bottom == 0){              
              that.setData({
                //scroll-view高度为屏幕高度减去上一个节点（'.title'）底部的纵坐标，单位为px
                scrollHeight: 320,
              })
            }
            else{              
              that.setData({
                //scroll-view高度为屏幕高度减去上一个节点（'.title'）底部的纵坐标，单位为px
                scrollHeight: height - rect.bottom - 10,
              })              
            }            
          }).exec()
        }
      })
    }, 1000) 
  },
  loadCity: function(longitude, latitude) {   //根据经纬度调用百度地图API获取城市名
    var page = this
    wx.request({
      url: 'https://api.map.baidu.com/geocoder/v2/?ak=ZenlWcczwXIAsrvdnGvFkdCSTRxWSXep&location=' + latitude + ',' + longitude + '&output=json',
      data: {},
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        // success         
        var city = res.data.result.addressComponent.city
        var lng = res.data.result.location.lng
        var lat = res.data.result.location.lat            
        page.setData({
          currentCity: city,
          lng: lng,
          lat: lat
        })
        page.loadPage(city, lng, lat)
      },
      fail: function() {
        page.setData({
          currentCity: "获取定位失败"
        })
      },
    })
  },
  loadPage: function(city, lng, lat) { //加载页面选择城市信息
    var that = this;
    wx.request({
      url: app.globalData.url + '/metro/root',
      header: {
        'charset': 'utf-8',
        'content-type': 'application/json' // 默认值
      },
      method: 'POST',
      data: {
        long: lng,
        lat: lat,
        c_name: city
      },
      success: function(res) {        
        if (res.statusCode != 200) return;
        if (that.data.lng == ""){
          that.setData({
            citylist: res.data.c_list,
            current_city: res.data.cur_city_name,
            current_code: res.data.cur_city_code,
            near_station: "未授权地理位置",
            near_line: "",
            cur_city_py: "http://ditie.114huoche.com/map/shanghai.jpg",
            currentCity: "上海市"
          })
        }
        else{
          that.setData({
            citylist: res.data.c_list,
            current_city: res.data.cur_city_name,
            current_code: res.data.cur_city_code,                       
          })
        }
        that.loadLine(that.data.current_code)              
      }      
    })
  },
  loadLine: function(current_code) {    //加载col-3线路信息
    var that = this    
    wx.request({
      url: app.globalData.url + '/metro/city',
      header: {
        'charset': 'utf-8',
        'content-type': 'application/json' // 默认值
      },
      method: 'POST',
      data: {
        c_code: current_code
      },
      success: function(res) {        
        var line_code = res.data.l_list[0].l_code
        var city_long = res.data.c_long
        var city_lat = res.data.c_lat        
        if (res.statusCode != 200) return;
        console.log(res.data)
        that.setData({
          linelist: res.data.l_list,
          line_code: res.data.l_list[0].l_code,
          city_long: res.data.c_long,
          city_lat: res.data.c_lat
        });
        that.loadStation(current_code, that.data.line_code);
        that.loadWeather(that.data.city_long, that.data.city_lat);
      }
    })
  },
  loadStation: function(current_code, line_code) { //加载col-9站名信息
    var that = this;
    wx.request({
      url: app.globalData.url + '/metro/line',
      header: {
        'charset': 'utf-8',
        'content-type': 'application/json' // 默认值
      },
      method: 'POST',
      data: {
        c_code: current_code,
        l_code: line_code
      },
      success: function(res) {        
        if (res.statusCode != 200) return;        
        that.setData({
          stationlist: res.data.l_dir[1],
          stationlist2: res.data.l_dir[0],
          fromline: res.data.l_ter[0].s_name,
          toline: res.data.l_ter[1].s_name
        });
      }
    })
  },
  loadWeather: function(longitude, latitude) {    //加载选择城市的天气信息
    var that = this;
    wx.request({
      url: "https://api.map.baidu.com/telematics/v3/weather?location=" + longitude + "," + latitude + "&output=json&ak=ZenlWcczwXIAsrvdnGvFkdCSTRxWSXep",
      success: function(res) {
        var pm25 = res.data.results[0].pm25;
        var air_quality = ""
        if (pm25 < 50) {
          air_quality = "优"
        } else if (50 <= pm25 && pm25 < 100) {
          air_quality = "良"
        } else if (100 <= pm25 && pm25 < 150) {
          air_quality = "轻度污染"
        } else if (150 <= pm25 && pm25 < 200) {
          air_quality = "中度污染"
        } else if (200 <= pm25 && pm25 < 300) {
          air_quality = "重度污染"
        } else if (pm25 >= 300) {
          air_quality = "严重污染"
        }        
        that.setData({
          cityname: res.data.results[0].currentCity,
          pm25: res.data.results[0].pm25,
          air_quality: air_quality,
          temperature: res.data.results[0].weather_data[0].temperature,
          weather: res.data.results[0].weather_data[0].weather          
        });
      }
    })
  },
  changecity: function(e) {     //切换城市 
    var c_code = e.target.dataset.code;
    var c_name = e.target.dataset.name;
    var c_py = e.target.dataset.py;    
    this.loadLine(c_code);
    this.closecitylist();
    this.setData({
      current_code: c_code,
      current_city: c_name,
      line_id: 0,
      cur_city_py: "http://ditie.114huoche.com/map/" + c_py + ".jpg",
    });
  },
  showcitylist: function() {    //展开选择城市地铁列表
    this.setData({
      cityshow: true,
      display: "block",
      showorclose: "closecitylist",
      cityshowimg: "up-circle"
    })
  },
  closecitylist: function() {   //收起选择城市地铁列表
    this.setData({
      cityshow: false,
      display: "none",
      showorclose: "showcitylist",
      cityshowimg: "down-circle"
    })
  },
  changeColorAndStation: function(e) { //点击线路改变hover样式
    var currentid = e.target.dataset.id;
    var c_code = this.data.current_code;
    var line_code = e.target.dataset.lcode;
    this.loadStation(c_code, line_code);
    this.setData({
      line_id: currentid
    })
  },
  changeline: function () {    //切换线路1
    this.setData({
      bgcolor: '#669999',
      textcolor: '#fff',
      showstatus: 'block',
      bgcolor2: '#fff',
      textcolor2: '#669999',
      showstatus2: 'none'
    })
  },
  changeline2: function () {   //切换线路2
    this.setData({
      bgcolor: '#fff',
      textcolor: '#669999',
      showstatus: 'none',
      bgcolor2: '#669999',
      textcolor2: '#fff',
      showstatus2: 'block',
    })
  },
  redirectmetro: function () {    //跳转附近地铁
    if (this.data.lng == "") {    //如果用户未授权，显示授权地理位置教程
      this.show_location_Course()
    }
    else {
      wx.navigateTo({
        url: '../map/map?title=地铁',
      })
    }
  },
  redirectbus: function () {     //跳转附近公交
    if (this.data.lng == "") {   //如果用户未授权，显示授权地理位置教程
      this.show_location_Course()
    }
    else {
      wx.navigateTo({
        url: '../map/map?title=公交',
      })
    }
  },
  redirectweather: function () {    //跳转天气查询
    if (this.data.lng == "") {      //如果用户未授权，显示授权地理位置教程
      this.show_location_Course()
    }
    else {
      wx.navigateTo({
        url: '../weather/weather',
      })
    }
  },
  show_metro_pic: function () {   //点击显示地铁图模态框
    this.setData({
      modalHidden: false
    })
  },
  modalCancel: function () {    //模态框点击取消
    this.setData({
      modalHidden: true
    })
  },
  modalConfirm: function () {   //模态框点击确认
    this.setData({
      modalHidden: true
    })
  },
  show_location_Course: function () {   //点击显示授权地理位置教程模态框
    this.setData({
      locationmodalHidden: false
    })
  },
  locationmodalCancel: function () {    //模态框点击取消
    this.setData({
      locationmodalHidden: true
    })
  },
  locationmodalConfirm: function () {   //模态框点击确认
    this.setData({
      locationmodalHidden: true
    })
  },
  show_pay_modal: function () {   //点击显示支付模态框
    this.setData({
      paymodalHidden: false
    })
  },
  paymodalCancel: function () {   //模态框点击取消
    this.setData({
      paymodalHidden: true
    })
  },
  paymodalConfirm: function () {    //模态框点击确认
    this.setData({
      paymodalHidden: true
    })
  },
  previewImage: function (e) {   //点击地铁图片浏览保存
    var current = e.target.dataset.src;
    var curcitypy = e.target.dataset.curcitypy; // 获取城市拼音
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: [curcitypy] 
      // 需要预览的图片http链接列表
    })
  },
  previewLocationImage: function (e) {    //点击教程图片浏览保存
    var current = e.target.dataset.src;
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: ['https://tstring.cn/images/jiaocheng.png'] // 需要预览的图片http链接列表
    })
  },  
  previewpayImage: function (e) {   //点击赞赏图片浏览保存
    var current = e.target.dataset.src;
    wx.previewImage({
      current: current,     // 当前显示图片的http链接
      urls: ['https://gss0.baidu.com/-Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/43a7d933c895d143fee15a247ef082025aaf0725.jpg'] // 需要预览的图片http链接列表
    })
  },  
  onShareAppMessage: function () { //用户点击右上角分享   
    return {
      title: '篮子地铁分享', // 分享标题
      desc: '地铁信息分享', // 分享描述
      path: 'pages/metro/metro' // 分享路径
    }
  },
  //滑动开始事件
  handletouchtart: function(e) {
    this.data.lastY = e.touches[0].pageY;
    if (!this.data.cityshow) //关闭
    {
      return;
    } else { //打开
      if (this.data.lastY >= 400) { //如果用户点击大于d等于400收起选择城市view       
        this.setData({
          cityshow: false,
          display: "none",
          showorclose: "showcitylist"
        })
      } else { //如果用户点击小于400跳过
        return;
      }
    }
  },  
  plus: function () {   //右下角点击弹出
    if (this.data.isPopping) {
      //缩回动画
      this.takeback()
      setTimeout(() => {
        this.setData({
          isPopping: false,
          is_hidden: true
        })
      }, 500)      
    } else if (!this.data.isPopping) {
      //弹出动画
      this.setData({
        isPopping: true,
        is_hidden: false
      })
      this.popp()      
    }
  },
  popp: function () {   //弹出动画
    //plus顺时针旋转
    var animationPlus = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })        
    var animationWxservice = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    animationPlus.rotateZ(90).step();       //PLUS旋转90°
    animationWxservice.opacity(1).step()    //item逐渐显示
    this.setData({
      animPlus: animationPlus.export(),       
      animWxservice: animationWxservice.export(),
    })
  },  
  takeback: function () {   //收回动画
    //plus逆时针旋转
    var animationPlus = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })       
    var animationWxservice = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    animationPlus.rotateZ(0).step()      
    animationWxservice.translate(0, 0).rotateZ(0).opacity(0).step()
    this.setData({
      animPlus: animationPlus.export(),     
      animWxservice: animationWxservice.export(),
    })
  }

})
